/**
 * 
 */
package com.xxl.job.admin.core.open.dingtalk;

import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.KeyManager;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

/**
 * 描述：
 * 
 * <pre>
 * SSL连接工具类
 * </pre>
 * 
 * @author qizai
 * @version: 0.0.1 2021年6月24日-下午1:52:15
 *
 */
public class SSLSocketUtil {
	/**
	 * 允许URL的主机名和服务器的标识主机名不匹配的情况
	 */
	public static HostnameVerifier		HOSTNAME_VERIFIER_TRUE	= null;
	/**
	 * 不允许URL的主机名和服务器的标识主机名不匹配的情况
	 */
	public static HostnameVerifier		HOSTNAME_VERIFIER_FALSE	= null;

	private static SSLContext			ctx						= null;
	private static SSLSocketFactory		socketFactory			= null;
	public static TrustManager[]		TRUST_MANAGERS			= null;
	public static DefaultTrustManager	DEFAULT_TRUST_MANAGER	= null;
	static {
		HOSTNAME_VERIFIER_TRUE = new HostnameVerifier() {
			@Override
			public boolean verify(String s, SSLSession sslSession) {
				return true;
			}
		};
		HOSTNAME_VERIFIER_FALSE = new HostnameVerifier() {
			@Override
			public boolean verify(String s, SSLSession sslSession) {
				return false;
			}
		};
		DEFAULT_TRUST_MANAGER = new DefaultTrustManager();
		TRUST_MANAGERS = new TrustManager[] { DEFAULT_TRUST_MANAGER };
		try {
			ctx = SSLContext.getInstance("TLS");
			ctx.init(new KeyManager[0], TRUST_MANAGERS, new SecureRandom());
			ctx.getClientSessionContext().setSessionTimeout(15);
			ctx.getClientSessionContext().setSessionCacheSize(1000);
			socketFactory = ctx.getSocketFactory();
		} catch (Exception e) {
		}
	}

	/**
	 * @return the {@link #ctx}
	 */
	public static SSLContext getCtx() {
		return ctx;
	}

	/**
	 * @return the {@link #socketFactory}
	 */
	public static SSLSocketFactory getSocketFactory() {
		return socketFactory;
	}

	/**
	 * @return the {@link #TRUST_MANAGERS}
	 */
	public static TrustManager[] getTrustManagers() {
		return TRUST_MANAGERS;
	}

	private static class DefaultTrustManager implements X509TrustManager {
		public X509Certificate[] getAcceptedIssuers() {
			return new X509Certificate[] {};
		}

		public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
		}

		public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
		}
	}
}
